﻿using Bricks.Business.Models.Account;
using Bricks.Business.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils;
using Bricks.Component.Utils.Extensions;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 机构管理
    /// </summary>
    [Export]
    public class OrgInfoController : BaseController
    {
        [Import]
        public IOrgInfoService OrgInfoService { get; set; }

        /// <summary>
        /// 机构管理首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.TreePanelInfo = base.GetPanelInfo();
            ViewBag.TreeToolBarInfo = base.GetToolBarInfo();

            //string orgMenuID = Request["MenuID"] as string;  //取得机构菜单ID
            //string embedUrl = Request.Url.OriginalString.Replace("OrgInfo", "Account").Replace(orgMenuID, OrgInfoService.GetAccountPageID());
            ////ViewBag.EmbedInfo = HttpHelper.GetPageHtml("~/Account/Index?MenuID=b4965782-329a-4a33-82ec-a8353e7054eb", null);  //取用户管理嵌入窗体（此处需要更改地址获取方式）
            //ViewBag.EmbedInfo = HttpHelper.GetPageHtml(embedUrl, null);  //取用户管理嵌入窗体（此处需要更改地址获取方式）
            return View();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDataList(string exceptAll)
        {
            var queryData = OrgInfoService.Orgs.OrderBy(m => m.OrderNo).ToList();
            if (exceptAll != "True")
            {
                OrgInfo nullOrg = new OrgInfo();
                nullOrg.ID = Guid.Empty;
                nullOrg.OrgName = "查看所有";
                queryData.Insert(0, nullOrg);
            }
            var data = from m in queryData
                       select new
                       {
                           iconCls = "icon-application",  //固定字段，作为treeField的图标
                           m.ID,
                           m.OrgName,
                           m.OrgCode,
                           m.Email,
                           m.Contactphone,
                           m.OrderNo,
                           m.PID,
                           OrgTypeString = GetOrgTypeString(m.OrgType),
                           m.Description,
                           m.IsDeleted,
                           m.AddDate
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 取得机构类型的枚举描述
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetOrgTypeString(OrgType type)
        {
            string result = MenuType.Null.ToDescription();  //取得中文描述（扩展方法）
            switch (type)
            {

                case OrgType.Null: result = OrgType.Null.ToDescription(); break;
                case OrgType.Company: result = OrgType.Company.ToDescription(); break;
                case OrgType.Department: result = OrgType.Department.ToDescription(); break;
                case OrgType.Position: result = OrgType.Position.ToDescription(); break;
            }
            return result;
        }

        /// <summary>
        /// 编辑初始页
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult Edit(string id, string pid)
        {
            OrgInfo model = new OrgInfo();
            ///如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = Guid.Parse(id);
                var record = OrgInfoService.Orgs.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record;
                    if (!model.PID.HasValue)
                        model.PID = Guid.Empty;
                }
            }
            //如果是新增
            else
            {
                //如果选中了节点，点新增，那么则将其父级设置为选中的节点
                if (!String.IsNullOrEmpty(pid))
                {
                    model.PID = Guid.Parse(pid);
                }
                else
                {
                    model.PID = Guid.Empty;
                }
                //机构类型默认为：无指定
                model.OrgTypeNum = (int)OrgType.Null;
            }
            return View(model);
        }

        /// <summary>
        /// 编辑（响应Post）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(OrgInfo model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            var record = OrgInfoService.Orgs.FirstOrDefault(m => m.ID == model.ID);

            //如果选择了无父级，那应该把PID置空
            if (model.PID.Equals(Guid.Empty))
                model.PID = null;
            //新增
            if (record == null)
            {
                if (OrgInfoService.IsExistOrgCode(model, false))
                    result = new OperationResult(OperationResultType.Warning, string.Format("机构编码[{0}]已存在，请重输", model.OrgCode));
                else
                    result = OrgInfoService.Add(model);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //修改
            else
            {
                if (OrgInfoService.IsExistOrgCode(model, true))
                    result = new OperationResult(OperationResultType.Warning, string.Format("机构编码[{0}]已存在，请重输", model.OrgCode));
                else
                    result = OrgInfoService.Modify(model);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //return View();
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取下拉树（选择父级使用）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrgComboTree(string emptyStr = "无父级")
        {
            var queryData = OrgInfoService.Orgs.OrderBy(m => m.OrderNo).ToList();

            //添加无父级节点
            OrgInfo nullParent = new OrgInfo();
            nullParent.ID = Guid.Empty;
            nullParent.OrgName = emptyStr;
            nullParent.PID = null;
            queryData.Insert(0, nullParent);  //插入到第一个

            var data = from m in queryData
                       select new
                       {
                           iconCls = "icon-application",  //固定字段，作为treeField的图标
                           id = m.ID,
                           text = m.OrgName,
                           parent = m.PID,
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            Guid guidID = id.ToGuid();
            var exeResult = OrgInfoService.Delete(guidID);
            return Json(exeResult);
        }

        /// <summary>
        /// 排序设置
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="pid">PID</param>
        /// <param name="order">排序</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetOrder(string id, string pid, string order)
        {
            //var exeResult = new OperationResult(OperationResultType.Success, "abc");
            //return Json(exeResult);

            Guid guidID = id.ToGuid();
            Guid? guidPID = pid.ToGuid();
            if (guidPID.Equals(Guid.Empty))
                guidPID = null;

            var exeResult = OrgInfoService.SetOrder(guidID, guidPID, order);
            return Json(exeResult);
        }
    }
}
